package com.xique.park.command.handler.base;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.park.api.IParkIpcCommandApi;
import com.xique.park.bean.domain.CommandInfo;
import com.xique.park.constant.CommandConstant;
import com.xique.park.service.command.service.IParkIpcCommandService;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * 设备命令基础类
 *
 * @author WLD
 */
@Slf4j
@Setter
@Getter
@Component
public abstract class BaseCommand implements Command {

    @Autowired
    private IParkIpcCommandApi parkIpcCommandApi;

    @Autowired
    private IParkIpcCommandService parkIpcCommandService;

    private static final String MQTT_KEY_KEY = "mqtt_key";
    private static final String MQTT_KEY_VALUE = "";

    private static final String CHARSET_KEY = "charset";

    private static final String SERVICE_KEY = "service";

    private static final String VERSION_KEY = "version";

    private static final String SIGN_KEY = "sign";
    private static final String SIGN_VALUE = "123456789456";

    private static final String TS_KEY = "ts";

    private static final String DEVICE_CODE_KEY = "device_code";

    /**
     * 接口处理成功
     */
    private static final int OK = 0;

    /**
     * 请求命令，需要应答
     */
    private static final int REQ_RSP = 1;
    /**
     * 请求命令，不需要应答
     */
    private static final int REQ_NORSP = 2;

    @Override
    public AjaxResult issue(Long parkId, String sn, String cmd) {
        return issue(parkId, null, null, sn, null, null, cmd);
    }

    @SuppressWarnings("unchecked")
    @Override
    public AjaxResult issue(Long parkId, Long laneId, String mngTypeIds, String sn, MultipartFile file, String fileName, String cmd) {
        String serviceName = getServiceName();
        String version = getVersion();

        JSONObject baseObj = getBaseObj(sn, serviceName, version);

        Map<String, Object> params = JSON.toJavaObject(baseObj, Map.class);

        AjaxResult issueResult = parkIpcCommandApi.issue(params);

        log.info("[停车系统]设备命令下发，服务名：{}，版本号：{}，车场ID：{}，设备编号：{}，下发参数：{}，下发结果：{}",
                serviceName, version, parkId, sn, params, issueResult);

        updateCommonInfo(cmd, params, issueResult);

        return issueResult;
    }

    protected void updateCommonInfo(String cmd, Map<String, Object> params, AjaxResult issueResult) {
        if (issueResult.get(CommandConstant.DATA) != null) {
            CommandInfo commandInfo = new CommandInfo();
            commandInfo.setCmd(Integer.valueOf(cmd));
            commandInfo.setSendContent(JSON.toJSONString(params));
            commandInfo.setAckContent(issueResult.get(CommandConstant.DATA).toString());
            parkIpcCommandService.updateByCmd(commandInfo);
        }
    }

    protected JSONObject getBaseObj(String sn, String serviceName, String version) {
        JSONObject obj = new JSONObject();
        obj.put(MQTT_KEY_KEY, MQTT_KEY_VALUE);
        obj.put(CHARSET_KEY, CharsetUtil.UTF_8);
        obj.put(SERVICE_KEY, serviceName);
        obj.put(VERSION_KEY, version);
        obj.put(SIGN_KEY, SIGN_VALUE);
        obj.put(TS_KEY, System.currentTimeMillis() / 1000);
        obj.put(DEVICE_CODE_KEY, sn);
        return obj;
    }

    protected void checkParkId(Long parkId) {
        if (parkId == null) {
            throw new IllegalArgumentException("车场参数错误，不可为空");
        }
    }

    protected void checkSn(String sn) {
        if (StrUtil.isBlank(sn)) {
            throw new IllegalArgumentException("设备号错误，不可为空");
        }
    }

    protected void checkLaneId(Long laneId) {
        if (laneId == null) {
            throw new IllegalArgumentException("通道参数错误，不可为空");
        }
    }

    protected void checkMngTypeIds(String mngTypeIds) {
        if (StrUtil.isBlank(mngTypeIds)) {
            throw new IllegalArgumentException("车辆管理类型错误，不可为空");
        }
    }

    protected void checkFileName(String fileName) {
        if (StrUtil.isBlank(fileName)) {
            throw new IllegalArgumentException("文件名错误，不可为空");
        }
    }
}
